package com.mq.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtil {
    private static final String SECRET_KEY = "secret";

    //接收业务数据，生成token返回
    public static String genToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + 60 * 60 * 1000))
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }
    //验证token，返回业务数据
    public static Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET_KEY)).
                build().
                verify(token).
//                getClaim("claims").
                getClaim("claims").
                asMap();

    }
}
//
//package com.newskill.utils;
//
//import com.auth0.jwt.JWT;
//import com.auth0.jwt.algorithms.Algorithm;
//import com.auth0.jwt.JWTVerifier;
//import com.auth0.jwt.exceptions.JWTVerificationException;
//
//import java.util.Date;
//import java.util.Map;
//import java.util.stream.Collectors;
//
//public class JwtUtil {
//    private static final String SECRET_KEY = "secret";
//
//    // 接收业务数据，生成token返回
//    public static String genToken(Map<String, Object> claims) {
//        return JWT.create()
//                .withClaim("claims", claims) // 直接使用 withClaims 方法
//                .withExpiresAt(new Date(System.currentTimeMillis() + 60 * 60 * 1000))
//                .sign(Algorithm.HMAC256(SECRET_KEY));
//    }
//
//    // 验证token，返回业务数据
//    public static Map<String, Object> parseToken(String token) {
//        try {
//            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
//            return verifier.verify(token).getClaims().entrySet().stream()
//                    .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().as(Object.class)));
//        } catch (JWTVerificationException exception) {
//            // Token 无效或已过期
//            throw new RuntimeException("Invalid or expired token", exception);
//        }
//    }
//}
